<script setup>

import {reactive, ref, watch} from "vue";
import {pageList} from "../app/api/EntityApi.js";
import {apiAppRel, getAppByApiId} from "./api/EntityApi.js";
import {PaginationDTO} from "../../model/PaginationDTO.js";
import {ElMessage} from "element-plus";

let props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  form: {
    type: Object,
    default: {}
  },
})

// 定义更新函数
const emit = defineEmits(['update:dialogVisible', 'refresh'])

const paginationDTO = new PaginationDTO({});

let tableData = ref([]);
// 查询参数
let pageNum = ref(1)
let pageSize = ref(10)
let totalNum = ref(0)
let criteria = reactive({});

paginationDTO.condition = criteria;

let selectedData = ref([]);
let sourceData = ref([]);

const cancel = () => {
  emit('update:dialogVisible', false)
  emit('refresh');
};

const saveRel = () => {
  apiAppRel(props.form.id, selectedData.value).then((data) => {
    ElMessage.success("保存成功")
    cancel();
  })
}

const selectedDataLoad = () => {
  getAppByApiId(props.form.id).then((data) => {
    data.forEach(item => {
      selectedData.value.push(item.id)
    })
  })
}

//查询数据
const sourceDataLoad = () => {
  paginationDTO.pageSize = pageSize.value;
  paginationDTO.pageNum = pageNum.value;
  pageList(paginationDTO).then((data) => {
    if (data) {
      tableData.value = data.data
      pageSize.value = data.pageSize
      pageNum.value = data.pageNum
      totalNum.value = data.total

      sourceData.value = []
      tableData.value.forEach(item => {
        sourceData.value.push({'key': item.id, 'label': item.description})
      })
    }
  });
}

const filterMethod = (query, item) => {
  return item['label'].includes(query);
};

// 监听 dialogVisible 的变化
watch(() => props.dialogVisible, (newDialogVisible) => {
  if (newDialogVisible) {
    // 当 dialogVisible 变为 true 时，重新加载数据
    sourceDataLoad();
    selectedDataLoad();
  }
});
</script>

<template>
  <!--弹窗-新增-->
  <el-dialog v-model="props.dialogVisible" title="详情" width="40%" @close="cancel">
    <el-transfer
        v-model="selectedData"
        :data="sourceData"
        filterable
        :filter-method="filterMethod"
        filter-placeholder="请输入搜索内容"
        :titles="['源列表', '目标列表']"
        :button-texts="['移除', '添加']"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveRel">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
</style>